package com.example.springworkfront.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springworkfront.Dao.Healthy_statusRepository;
import com.example.springworkfront.Dao.HouseholdRepository;
import com.example.springworkfront.Entity.Healthy_status;
import com.example.springworkfront.Entity.Household;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.sql.SQLException;
import java.util.Map;

@Service
public class HouseholdServiceImpl implements HouseholdService {

    private static final String APPID="wxc23918cf06006326";
    private static final String SECRET="b4f0a6c441abceeba2896382690cacc3";
    private static final String GETOPENID_URI="https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}" +
            "&grant_type=authorization_code";
    private static final String QRCODE_URI="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
    private static final String ACCESS_TOKEN_URI="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
    private static final RestTemplate rest = new RestTemplate();

    @Autowired
    private HouseholdRepository householdRepository;
    @Autowired
    private Healthy_statusRepository healthy_statusRepository;

    @Override
    public String checkopenid(String openid) {

        Household household = householdRepository.findHouseholdByOpenid(openid);
        if (household!=null) {
            String json= JSON.toJSONString(household);
            System.out.println("aaaaaaaaaaaaaaaaaa");
            System.out.println(household.getIdCard());
            System.out.println(json);
            return json;
        }
        return null;
    }
    public String getopenid(String code){
        System.out.println(code);
        URI uri= UriComponentsBuilder
                .fromUriString(GETOPENID_URI)
                .buildAndExpand(APPID,SECRET, code)
                .toUri();
        RequestEntity<Void> requestEntity=RequestEntity
                .post(uri)
                .build();
        ResponseEntity<String> responseEntity = rest.exchange(requestEntity, String.class);
        JacksonJsonParser jacksonJsonParser=new JacksonJsonParser();
        Map<String,Object> map = jacksonJsonParser.parseMap(responseEntity.getBody());
        System.out.println(map);
        for(String keyString:map.keySet()) {
            if (keyString.equals("openid")) {
                return map.get("openid").toString();
            }
        }
        return null;
    }
    @ResponseBody
    public String upload(MultipartFile file, String account, String password, String name, String id_card,
                         String room_number, String openid,String phone) throws IOException, ServletException {
        if(householdRepository.findById(account)!=null)return "chongfu";
            else{
            System.out.println(account);
            String filename=account+".png";
            System.out.println(filename);

            File filex  =  new File("/tmp/",filename);
            file.transferTo(filex);
//            private String account;
//            private String name;
//            private String password;
//            private String img;
//            private String phone;
//            private String id_card;
//            private String room_number;
//            private String access_times;
//            private String openid;
//            private String status;
            Household household=new Household(account,name,password,filename,phone,id_card,room_number,0,openid,"健康");
            householdRepository.save(household);
            String json=JSON.toJSONString(household);
            return json;
            }
    }
    public String getqrcode(String account) {
        //获取access——token
        URI uri = UriComponentsBuilder
                .fromUriString(ACCESS_TOKEN_URI)
                .buildAndExpand(APPID, SECRET)
                .toUri();
        RequestEntity<Void> requestEntity = RequestEntity
                .post(uri)
                .build();
        ResponseEntity<String> responseEntity = rest.exchange(requestEntity, String.class);
        JacksonJsonParser jacksonJsonParser = new JacksonJsonParser();
        Map<String, Object> map = jacksonJsonParser.parseMap(responseEntity.getBody());
        System.out.println(map);
        String access_token = null;
        for (String keyString : map.keySet()) {
            if (keyString.equals("access_token")) {
                access_token = map.get("access_token").toString();
            }
        }
        //获取二维码图片地址
        URI urix = UriComponentsBuilder
                .fromUriString(QRCODE_URI)
                .buildAndExpand(access_token)
                .toUri();
        RequestEntity<Void> requestEntityx = RequestEntity
                .post(uri)
                .build();
        ResponseEntity<String> responseEntityx = rest.exchange(requestEntityx, String.class);
        JacksonJsonParser jacksonJsonParserx = new JacksonJsonParser();
        Map<String, Object> mapx = jacksonJsonParserx.parseMap(responseEntityx.getBody());
        System.out.println(mapx);
        for (String keyString : mapx.keySet()) {
            if (keyString.equals("access_token")) {
                access_token = map.get("access_token").toString();
            }
        }
        String url = QRCODE_URI + access_token;
        String data = "{\"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\":" + account + "}}}";
        String result="";
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            BasicResponseHandler handler = new BasicResponseHandler();
            StringEntity entity = new StringEntity(data, "utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            result = httpClient.execute(httpPost, handler);
            System.out.println(result);
            JSONObject jsonObject =JSONObject.parseObject(result);
            String ticket=jsonObject.getString("ticket");
            return ticket;
        } catch (Exception e) {
            e.printStackTrace();
        }
            return null;
        }

}